package technicalservices.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import domain.advertisement.Ad;

public class FileHandler {
	private String file;

	public FileHandler(String file) {
		if(isFile(file)) {
			try {
				new File(file).createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			this.file = file;
	}

	public void saveFile(List<?> ads) {
		ObjectOutputStream out;
		
		try {
			out = new ObjectOutputStream(new FileOutputStream(file));
			out.writeObject(ads);
			out.close();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	public List<?> loadFile() {
		List<?> list = new ArrayList();
		
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream( file));
			list = (List<?>) in.readObject();
			in.close();
		} catch (IOException ex) {
			System.out.println("FileHandler.loadFile() -> IOException: " + ex);
		} catch (ClassNotFoundException ex) {
			System.out.println("FileHandler.loadFile() -> ClassNotFoundException: " + ex);
		}
		
		return list;
	}

	public boolean isFile(String file) {
		return new File(file).exists();
	}
}
